package com.heima.a07_demo.server.controller;

import com.heima.a07_demo.common.context.BaseContext;
import com.heima.a07_demo.common.result.Result;
import com.heima.a07_demo.common.utils.AliOssUtil;
import com.heima.a07_demo.server.service.CommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private CommonService commonService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /*
     * 文件上传
     * */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException {
        log.info("文件上传:{}",file);
        String originalFileName=file.getOriginalFilename();
        String extension=originalFileName.substring(originalFileName.lastIndexOf("."));
        String objectName= UUID.randomUUID().toString()+extension;
        String filePath=aliOssUtil.upload(file.getBytes(),objectName);
        return Result.success(filePath);
    }
    /*
    *
    * 获取验证码
    * */
    @PostMapping("/code")
    public Result<String> getCode(@RequestParam String phoneNumber){
        log.info("获取到的手机号是:{}",phoneNumber);
        String code = commonService.sendMails();
        log.info("验证码的值为:{}",code);
        //将邮箱验证码保存到redis当中去
        //5分钟
        String key="A07:login:code:"+phoneNumber;
         stringRedisTemplate.opsForValue().set(key,code,5L, TimeUnit.MINUTES);
        return Result.success(code);
    }

}
